package com.qiangesoft.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiangesoft.security.pojo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理器
 *
 * @author qiangesoft
 * @date 2024-05-14
 */
@Slf4j
@Component
public class CustomAuthenticationFailHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("认证失败");

        String errorMessage = "用户名或密码错误";
        if (exception instanceof LockedException) {
            errorMessage = "账户被锁定!";
        } else if (exception instanceof InsufficientAuthenticationException) {
            errorMessage = "账户权限不足!";
        } else if (exception instanceof AccountExpiredException) {
            errorMessage = "账户已过期!";
        } else if (exception instanceof DisabledException) {
            errorMessage = "账户已禁用!";
        } else if (exception instanceof AuthenticationServiceException) {
            errorMessage = "认证失败，请重试!";
        }

        // 返回结果
        response.setContentType("application/json;charset=utf-8");
        String string = new ObjectMapper().writeValueAsString(ResultVO.fail(errorMessage));
        response.getWriter().write(string);
    }

}
